#include "MainWindow.h"
#include <QProcess>
#include <QRegExp>
#include <QValidator>

MainWindow::MainWindow() : QMainWindow(nullptr), m_ui(new Ui::MainWindow) {
	m_ui->setupUi(this);
	//对输入框进行限制
	QRegExp regExp("^[a-zA-Z0-9_\u4e00-\u9fa5]+$");
	QValidator* validator = new QRegExpValidator(regExp, this);
	m_ui->mBrandComboBox->setValidator(validator);
	m_ui->mTesterComboBox->setValidator(validator);
	m_ui->mScheduleComboBox->setValidator(validator);
	m_ui->mTestBatchLineEdit->setValidator(validator);
	m_ui->mTestNumLineEdit->setValidator(validator);
	//隐藏开发者按钮
	m_ui->developBtn->setVisible(false);
	m_ui->developHomeBtn->setVisible(false);
	//显示开发者按钮的快捷键
	m_devShortcut = new QShortcut(QKeySequence("Ctrl+D"), this);
	connect(m_devShortcut, &QShortcut::activated, this, [&] {
		qInfo() << "显示开发者按钮...";
		m_ui->developBtn->setVisible(true);
		m_ui->developHomeBtn->setVisible(true);
	});

	//显示首页
	m_ui->stackedWidget->setCurrentIndex(0);

	// 初始化3D
	initialVtkWidget();
	
	
}

MainWindow::~MainWindow() {
	delete m_ui;
	delete m_devShortcut;
}

void MainWindow::init() {
	
	QStringList errorMsg;
	//连接相机 scannerPreviewLabel
	try {
		m_app.connectCamera();
		connect(&m_app, &AppService::frameReceive, this, [&](cv::Mat& frame) {
			if (m_liveLabel && !frame.empty()) {
				ImageUtils::liveImage(m_liveLabel, frame);
			}
		});
		// 初始化3D数据传输信号槽
		connect(&m_app, &AppService::sendCloud2mainwindow, this, &MainWindow::processCloudData);
	} catch (const MyError& e) {
		qCritical() << e.desc();
		errorMsg.push_back(e.desc());
	}
	//连接串口
	try {
		m_app.connectSerialPort();//韦恩斯驱动
		m_app.connectServoPort();//伺服驱动
	} catch (const MyError& e) {
		qCritical() << e.desc();
		errorMsg.push_back(e.desc());
	}
	//连接数据库
	try {
		m_app.connectDatabase();
	} catch (const MyError& e) {
		qCritical() << e.desc();
		errorMsg.push_back(e.desc());
	}
	//若错误信息不为空，抛出异常
	if (errorMsg.size() > 0) {
		throw MyError(MyErrorType::INIT_ERROR);
	}
	initUI();
}

void MainWindow::initUI()
{
	qInfo() << tr("加载界面...");
	//测量结果表格最少的行数
	m_testTableMinRow = 13;
	//历史记录表默认行数
	m_historyTableMinRow = 23;
	//历史记录表默认行数
	m_historyDataTableMinRow = 23;
	//牌号信息表格默认行数
	m_brandTableMinRow = 26;
	//检测员信息表格默认行数
	m_testerTableMinRow = 26;
	//班次表格默认行数
	m_scheduleTableMinRow = 26;

	//设置项目名称，加载logo
	m_ui->headerLogoLabel->clear();
	m_ui->homeLogoLabel->clear();
	//if (!m_config.logoPath.homeLogo.isEmpty()) {
	//	m_ui->headerLogoLabel->setPixmap(QPixmap(QString::fromUtf8(m_config.logoPath.homeLogo.toUtf8())));
	//}
	//if (!m_config.logoPath.headerLogo.isEmpty()) {
	//	m_ui->homeLogoLabel->setPixmap(QPixmap(QString::fromUtf8(m_config.logoPath.headerLogo.toUtf8())));
	//}

	//初始化表格显示
	//this->initTable();

	////隐藏开发者按钮
	//m_ui->developBtn->setVisible(false);
	//m_ui->developBtn2->setVisible(false);

	////页面初始化
	//m_ui->stackedWidget->setCurrentIndex(0);
	//m_ui->contentWidget->setCurrentIndex(0);

	//查询检测参数
	queryTestParams();

	//检测参数初始化
	//resetTestParams();

	//查询菜单初始化，初始化查询日期
	QDate today = QDate::currentDate();
	m_ui->qBeginDateEdit->setDate(today);
	m_ui->qEndDateEdit->setDate(today);
}

void MainWindow::initialVtkWidget(){
	viewer.reset(new pcl::visualization::PCLVisualizer("viewer", false));
	vtkNew<vtkGenericOpenGLRenderWindow> window;
	window->AddRenderer(viewer->getRendererCollection()->GetFirstRenderer());
	m_ui->openGLWidget->SetRenderWindow(window.Get());
	viewer->setupInteractor(m_ui->openGLWidget->GetInteractor(),
	m_ui->openGLWidget->GetRenderWindow());
	m_ui->openGLWidget->update();
}

void MainWindow::showTestResult(QTableWidget* table, staticalParameters data)
{
	static int currentContentRows = 0;//单独记录插入次数
	this->insertValue2Table(table, currentContentRows, 0, data.maxZ);
    this->insertValue2Table(table, currentContentRows, 1, data.minZ);
    this->insertValue2Table(table, currentContentRows, 2, data.meanZ);
    this->insertValue2Table(table, currentContentRows, 3, data.stdZ);
    this->insertValue2Table(table, currentContentRows, 4, abs(data.maxZ - data.minZ));
	currentContentRows++;
	//将data数据复制给m_testData对应成员变量
	m_testData.setMaxHeight(data.maxZ);
    m_testData.setMinHeight(data.minZ);
    m_testData.setMeanHeight(data.meanZ);
    m_testData.setHeightSD(data.stdZ);
    m_testData.setAbnormalArea(abs(data.maxZ - data.minZ));
	//打开输入框
	
	m_ui->mBrandComboBox->setEnabled(true);
	m_ui->mTesterComboBox->setEnabled(true);
	m_ui->mScheduleComboBox->setEnabled(true);
	m_ui->mTestBatchLineEdit->setEnabled(true);
	m_ui->mTestNumLineEdit->setEnabled(true);
	//存储数据
	testFinishedHandle();
	//禁止在运行期间“测量按钮被二次”点击,其他按钮也应该启用
	m_ui->startTestBtn->setEnabled(true);//测量按钮
	m_ui->resetParamsBtn->setEnabled(true);//重置按钮
	m_ui->DrivenWheelControlBtn_2->setEnabled(true);//主轮涨紧
	m_ui->FollowedWheelControlBtn_2->setEnabled(true);//从轮涨紧
	m_ui->printTestDataBtn->setEnabled(true);//打印按钮
	m_ui->exportTestDataBtn->setEnabled(true);//导出按钮
	m_ui->deleteTestDataBtn->setEnabled(true);//删除按钮
	m_ui->clearTestDataBtn->setEnabled(true);//清空按钮
}

void MainWindow::addTestParams(QString paramType, QString name)
{
	if (!name.isEmpty()) {
		try {
			//提取QComboBox和QTableWidget组件名称
			QString componentName = paramType.toLower();
			componentName = paramType.at(0).toUpper() + paramType.mid(1);
			QComboBox* box = findChild<QComboBox*>(tr("m%1ComboBox").arg(componentName));
			QTableWidget* table = findChild<QTableWidget*>(tr("s%1TableWidget").arg(componentName));
			//判断是否存在相同的记录
			if (box->findText(name) == -1) {
				m_app.addSqlTestParam(paramType.toLower(), name);
				box->insertItem(0, name);
			}
		}
		catch (const MyError& e) {
			qCritical() << e.what();
		}
	}
}

void MainWindow::queryTestParams()
{
	try {
		if (!m_app.isDBOpen()) {
			return;
		}
		QComboBox* mTesterComboBox = m_ui->mTesterComboBox;
		QComboBox* mBrandComboBox = m_ui->mBrandComboBox;
		QComboBox* mScheduleComboBox = m_ui->mScheduleComboBox;
		QTableWidget* sTesterTableWidget = m_ui->sTesterTableWidget;
		QTableWidget* sBrandTableWidget = m_ui->sBrandTableWidget;
		QTableWidget* sScheduleTableWidget = m_ui->sScheduleTableWidget;
		//检测员，牌号，班次列表
		QStringList testerList, brandList, scheduleList;
		m_app.querySqlTestParam("tester", testerList);
		m_app.querySqlTestParam("brand", brandList);
		m_app.querySqlTestParam("schedule", scheduleList);
		
		//清空下拉框中的数据
		mTesterComboBox->clear();
		mBrandComboBox->clear();
		mScheduleComboBox->clear();
		//填充下拉框中的数据
		mTesterComboBox->addItems(testerList);
		mBrandComboBox->addItems(brandList);
		mScheduleComboBox->addItems(scheduleList);
		//重置表格行数，并填充数据
		TableUtils::restTable(sTesterTableWidget, max(m_testerTableMinRow, testerList.size()));
		TableUtils::restTable(sBrandTableWidget, max(m_brandTableMinRow, brandList.size()));
		TableUtils::restTable(sScheduleTableWidget, max(m_scheduleTableMinRow, scheduleList.size()));
		//向检测员表格中填充数据
		for (int i = 0; i < testerList.size(); i++) {
			TableUtils::insertValue2Table(sTesterTableWidget, i, 0, testerList[i]);
		}
		//向牌号表格中填充数据
		for (int i = 0; i < brandList.size(); i++) {
			TableUtils::insertValue2Table(sBrandTableWidget, i, 0, brandList[i]);
		}
		//向班次表格中填充数据
		for (int i = 0; i < scheduleList.size(); i++) {
			TableUtils::insertValue2Table(sScheduleTableWidget, i, 0, scheduleList[i]);
		}
	}
	catch (const std::exception& e) {
		qCritical() << e.what();
	}
}

void MainWindow::insertValue2Table(QTableWidget* table, int row, int col, QVariant val, int decimal, int alignment)
{
	//转换数据
	QString text;
	if (val.type() == QMetaType::Float || val.type() == QMetaType::Double) {
		text = QString::number(val.toDouble(), 'f', decimal);
	}
	else {
		text = val.toString();
	}
	//填充数据
	QTableWidgetItem* item = new QTableWidgetItem(text.isEmpty() ? "" : text);
	item->setTextAlignment(alignment);
	if (text.endsWith("↓") || text.endsWith("↑")) {
		item->setTextColor(QColor(255, 0, 0));
	}
	// 如果当前行数不够，就新增一行
	if (table->rowCount() <= row) {
		table->insertRow(table->rowCount()); // 在末尾插入新行
	}
	table->setItem(row, col, item);
	table->scrollToBottom();
}

void MainWindow::queryTestRecord(QDate& beginDay, QDate& endDay, QString tester, QString schedule)
{
	if (!m_app.isDBOpen()) {
		return;
	}
	try {
		//清空显示结果的表格
		QTableWidget* table = m_ui->qResultTable_2;
		TableUtils::restTable(table, m_historyDataTableMinRow);
		//获取检测记录表格
		table = m_ui->qResultTable;
		//查询记录
		QList<DaoModel::TestData>records;
		m_app.querySqlTestRecords(records,beginDay, endDay, tester, schedule);
		//清空表格，保证表格的行数不低于HISTORY_TABLE_ROW_MIN
		TableUtils::restTable(table,max(records.size(), m_historyDataTableMinRow));
		//向表中填充数据
		for (int i = 0; i < records.size(); i++) {
			DaoModel::TestData& record = records[i];
			//检测时间
			TableUtils::insertValue2Table(table, i, 0, record.createTime().toString(TimeUtils::DATETIME_FORMAT));
			//检测员
			TableUtils::insertValue2Table(table, i, 1, record.tester());
			//班次
			TableUtils::insertValue2Table(table, i, 2, record.schedule());
		}
	}catch (const MyError& e) {
		qCritical() << e.code();
	}catch (const std::exception& e) {
		qCritical() << e.what();
	}
}

void MainWindow::objClicked(std::function<void()> objFunction, int timeout) {
	QWidget* obj = qobject_cast<QAbstractButton*>(sender());
	qInfo() << obj->objectName() << " clicked...";
	//禁用组件
	obj->setEnabled(false);
	//执行点击事件
	objFunction();
	//100ms后将接收点击事件的组件启用
	QTimer::singleShot(timeout, [=]{ obj->setEnabled(true); });
}

void MainWindow::resetMotoParams() {
	SerialPortConfig& config = m_app.getConfig().serialPortConfig;
	m_ui->sScanSpeedSpinBox->setValue(config.scannSpeed);
	m_ui->sBackSpeedSpinBox->setValue(config.backSpeed);
	m_ui->sEQuickenSpinBox->setValue(config.eQuicken);
	m_ui->sEWorkSpinBox->setValue(config.eWork);
	m_ui->sEAwaitSpinBox->setValue(config.eAwait);
	m_ui->sAcceleratedSpinBox->setValue(config.accelerated);
	m_ui->sRetardedSpinBox->setValue(config.retarded);
	m_ui->sMotoMcsSpinBox->setValue(config.motoMcs);
	
	if (config.rotateDirection == 1) {
		m_ui->rotateDirComBX->setCurrentIndex(0);
	}
	else if (config.rotateDirection == 0) {
		m_ui->rotateDirComBX->setCurrentIndex(1);
	}
	m_ui->rotateCountSpinBox->setValue(config.rotateCount);
}

void MainWindow::resetCameraParams() {
	CameraConfig& config = m_app.getConfig().camera;
	m_ui->cameraGainSpinBox->setValue(config.gain);
	m_ui->cameraExposureTimeSpinBox->setValue(config.exposure);
	m_ui->cameraWBRDoubleSpinBox->setValue(config.whiteBalanceRed);
	m_ui->cameraWBGDoubleSpinBox->setValue(config.whiteBalanceGreen);
	m_ui->cameraWBBDoubleSpinBox->setValue(config.whiteBalanceBlue);
	m_ui->cameraFrameBeginXSpinBox->setValue(config.offsetX);
	m_ui->cameraFrameBeginYSpinBox->setValue(config.offsetY);
	m_ui->cameraFrameHeightSpinBox->setValue(config.frameHeight);
	m_ui->cameraFrameWidthSpinBox->setValue(config.frameWidth);
	m_ui->cameraFPSSpinBox->setValue(config.fps);
	m_ui->cameraFrameCountSpinBox->setValue(config.frameCount);
}

bool MainWindow::checkTestParams(DaoModel::TestData& data) {
	//获取参数组件
	data.setCreateTime(QDateTime::currentDateTime());
	data.setId(data.createTime().toMSecsSinceEpoch());
	data.setNum(m_ui->mTestNumLineEdit->text().trimmed());
	data.setBrand(m_ui->mBrandComboBox->currentText().trimmed());
	data.setTester(m_ui->mTesterComboBox->currentText().trimmed());
	data.setSchedule(m_ui->mScheduleComboBox->currentText().trimmed());
	//校验检测编号
	if (data.num().isEmpty()) {
		if (MyMessageBox::warning(this, "请输入编号", "自动填入", "关闭")) {
			data.setNum(QDateTime::currentDateTime().toString("yyMMddHHmmss"));
			m_ui->mTestNumLineEdit->setText(data.num());
		}
		else {
			return false;
		}
	}
	//检查是否有重复样本
	for (int i = 0; i < m_testDataList.size(); i++) {
		DaoModel::TestData& oldData = m_testDataList[i];
		if (data.brand() == oldData.brand() && data.num() == oldData.num()) {
			if (MyMessageBox::warning(this, "当前样本已经测量完成，点击确认按钮将会覆盖以前的数据", "确认", "取消") == 0) {
				return false;
			}
		}
	}
	//判断是否是第一次检测
	if (m_testDataList.empty()) {
		//更新检测时间
		m_testTime = QDateTime::currentDateTime();
	}
	return true;
}

void MainWindow::menuBtnClicked(std::function<int()> btnClicked) {
	QAbstractButton* btn = qobject_cast<QAbstractButton*>(sender());
	qInfo() << btn->objectName() << "clicked...";
	//禁用组件
	btn->setEnabled(false);
	//获取按钮点击前的状态
	bool beforeStatus = !btn->isChecked();
	//防止发生异常的时候按钮是被选中状态
	btn->setChecked(false);
	//执行按钮点击事件，并切换页面
	int pageNum = 0;
	try {
		pageNum = btnClicked();
		//查询所有的按钮
		for (QAbstractButton* obj : m_ui->menuBtnsFrame->findChildren<QAbstractButton*>()) {
			obj->setChecked(obj == btn);
		}
		m_ui->stackedWidget->setCurrentIndex(1);
		m_ui->menuStackedWidget->setCurrentIndex(pageNum);
	} catch (const MyError& e) {
		//还原按钮的样式
		btn->setChecked(beforeStatus);
		qCritical() << e.desc();
	}
	//100ms后将接收点击事件的组件启用
	QTimer::singleShot(50, [=] { btn->setEnabled(true); });
}


//void MainWindow::processCloudData(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud){
//	// ========显示3D图像
//	viewer->removeAllPointClouds();
//	viewer->removeAllShapes();
//
//	//刷新渲染
//	m_ui->openGLWidget->GetRenderWindow()->Render();
//	viewer->setBackgroundColor(0, 0, 0);
//	pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> fildColor(cloud, "z");
//	viewer->removePointCloud("sample cloud");
//	viewer->addPointCloud<pcl::PointXYZ>(cloud, fildColor, "sample cloud");
//
//	viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
//
//	viewer->addCoordinateSystem(5.0);
//	viewer->initCameraParameters();
//	viewer->resetCamera();
//
//	m_ui->openGLWidget->GetRenderWindow()->Render();
//
//	while (!viewer->wasStopped()){
//		viewer->spinOnce(100);
//		std::chrono::milliseconds dura(100);
//		std::this_thread::sleep_for(dura);
//	}
//}

void MainWindow::processCloudData(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, staticalParameters cloudStaticalData) {
	// ======== 显示3D图像
	viewer->removeAllPointClouds();
	viewer->removeAllShapes();

	// 刷新渲染
	m_ui->openGLWidget->GetRenderWindow()->Render();
	viewer->setBackgroundColor(0, 0, 0);

	// 设置点云颜色
	pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> fieldColor(cloud, "z");
	viewer->addPointCloud<pcl::PointXYZ>(cloud, fieldColor, "sample cloud");
	viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");

	// 只添加一次坐标系
	static bool coordAdded = false;
	if (!coordAdded) {
		viewer->addCoordinateSystem(5.0);
		coordAdded = true;
	}

	viewer->initCameraParameters();
	viewer->resetCamera();

	// 立即渲染一次
	m_ui->openGLWidget->GetRenderWindow()->Render();

	// 仅在必要时手动刷新一次，而不是循环调用
	viewer->spinOnce(100);

	//将计算结果显示至表格中
	this->showTestResult(m_ui->measureTableWidget, cloudStaticalData);

	//m_app.losseFilm();
}


//void MainWindow::on_testBtn_clicked() {
//	//加载点云数据
//	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
//	QString filename = QFileDialog::getOpenFileName(this, tr("Open point cloud"), "F:\\TouMingZhi\\DataLunWen\\AllData\\LiQun\\test", tr("Point Cloud Data (*.pcd *.ply)"));
//	if (filename.isEmpty())
//	{
//		qDebug() << "文件打开失败！";
//		return;
//	}
//
//	qDebug() << "filename:" << filename;
//	int return_status;
//	if (filename.endsWith(".pcd", Qt::CaseInsensitive))
//	{
//		return_status = pcl::io::loadPCDFile(filename.toStdString(), *cloud);
//	}
//
//	if (return_status != 0)
//	{
//		PCL_ERROR("Error reading point cloud %s\n", filename.toStdString().c_str());
//		return;
//	}
//
//	// ========显示3D图像
//	viewer->removeAllPointClouds();
//	viewer->removeAllShapes();
//
//	//刷新渲染
//	m_ui->openGLWidget->GetRenderWindow()->Render();
//	viewer->setBackgroundColor(0, 0, 0);
//	pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> fildColor(cloud, "z");
//
//
//	viewer->removePointCloud("sample cloud");
//	viewer->addPointCloud<pcl::PointXYZ>(cloud, fildColor, "sample cloud");
//
//	viewer->setPointCloudRenderingProperties(
//		pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
//
//	viewer->addCoordinateSystem(5.0);
//	viewer->initCameraParameters();
//	viewer->resetCamera();
//
//	m_ui->openGLWidget->GetRenderWindow()->Render();
//
//	while (!viewer->wasStopped())
//	{
//		viewer->spinOnce(100);
//		std::chrono::milliseconds dura(100);
//		std::this_thread::sleep_for(dura);
//	}
//
//}




void MainWindow::testFinishedHandle()
{
	try {
		qDebug() << m_testData.toString();
		QTableWidget* table=m_ui->measureTableWidget;
		//删除重复样品
		for (int i = 0; i < m_testDataList.size(); i++) {
			DaoModel::TestData& data = m_testDataList[i];
			qDebug() << data.toString();
			if (data.brand() == m_testData.brand() && data.num() == m_testData.num()) {
				try {
					qDebug() << tr("删除重复数据...");
					m_app.deleteRecords(data.id());
				}
				catch (const MyError& e) {
					qCritical() << e.what();
					MyMessageBox::warning(this, tr("删除原始数据失败"), tr("关闭"));
				}
				qDebug() << tr("移除表格中的原数据...");
				//移除缓存数据
				m_testDataList.removeAt(i);
				table->removeRow(i);
				//重置表格行数
				table->setRowCount(max(m_testDataList.size(), m_testTableMinRow));
			}
		}
		qDebug() << tr("显示结果...");
		m_testDataList.push_back(m_testData);
		//保存数据
		try {
			qDebug() << tr("保存数据...");
			m_app.saveData(m_testData);

		}
		catch (const MyError& e) {
			qCritical() << e.what();
			MyMessageBox::warning(this, tr("数据保存失败"), tr("关闭"));
		}
	}catch (const MyError& e) {
		qCritical() << "处理检测结果异常";
	}
}

void MainWindow::queryHistoryTestParams()
{
	if (!m_app.isDBOpen()) {
		qDebug() << "查询历史";
		return;
	}
	try {
		qDebug() << "查询历史";
		QComboBox* qTesterComboBox = m_ui->qTesterComboBox;
		QComboBox* qScheduleComboBox = m_ui->qScheduleComboBox;
		//检测员，牌号，班次列表
		QStringList testerList, scheduleList;
		m_app.querySqlHistoryTestParams(testerList, scheduleList);
		//清空下拉框中的数据
		qTesterComboBox->clear();
		qScheduleComboBox->clear();
		//填充数据
		qTesterComboBox->addItems(testerList);
		qScheduleComboBox->addItems(scheduleList);
		qDebug() << "testerList:" << testerList;
		qDebug() << "scheduleList:" << scheduleList;
		//清空选项
		qTesterComboBox->setCurrentIndex(-1);
		qScheduleComboBox->setCurrentIndex(-1);
	}
	catch (const std::exception& e) {
		qCritical() << e.what();
	}
}

void MainWindow::onTestFinished(MyModel::TestData& data, const MyError& error) {
	MyLoading::stopLoading();
	if (error.code() == MyErrorType::NONE_ERROR.code) {
		data.recordId = m_testRecord.id;
		//保存数据
		try {
			m_app.saveTestData(data);

		} catch (const MyError& e) {
			qCritical() << e.desc();
			MyMessageBox::warning(this, "数据保存失败", "关闭");
		}
	}
}

void MainWindow::on_exitBtn_clicked() {
	objClicked([&] {
		if(MyMessageBox::warning(this, "是否要退出程序", "取消", "退出") == 0){
			try {
				m_app.closeSerialPort();
				m_app.closeCamera();
				m_app.clearDatabaseConnections();
			} catch(const MyError& e) {
				qCritical() << e.desc();
			}		
			emit close();
		}
	});
}

void MainWindow::on_homeBtn_clicked() {
	objClicked([&]{
		try {
			m_app.stopCameraLive();
		} catch(const MyError& e) {
			qCritical() << e.desc();
		}
		m_ui->stackedWidget->setCurrentIndex(0);
	});
}

void MainWindow::on_shutdownBtn_clicked() {
	objClicked([&]{
		if (MyMessageBox::warning(this, tr("是否要关机"), tr("取消"), tr("关机")) == 0) {
			system("shutdown -s -t 00");
		}
	});
}

void MainWindow::on_demarcateBtn_clicked() {
	menuBtnClicked([&] {
		return 0;
	});
}

void MainWindow::on_settingBtn_clicked() {
	menuBtnClicked([&] {
		return 1;
	});
}

void MainWindow::on_developBtn_clicked() { 
	menuBtnClicked([&] {
		m_liveLabel = m_ui->sLiveLabel;
		//重置运动平台参数
		resetMotoParams();
		//重置相机参数
		resetCameraParams();
		try {
			m_app.startCameraLive();
		} catch (const MyError& e) {
			qCritical() << e.desc();
			if (MyMessageBox::error(this, e.desc(), "继续", "取消") == 0) {
				throw e;
			}
		}
		return 2;
	});
}

void MainWindow::on_measureBtn_clicked() {
	menuBtnClicked([&]() {
		m_liveLabel = m_ui->scannerPreviewLabel;
		try {
			m_ui->torsionLabel->clear();
			//m_app.startCameraLive();
		} catch (const MyError& e) {
			qCritical() << e.desc();
			if (MyMessageBox::error(this, e.desc(), "继续", "取消") == 0) {
				throw e;
			}
		}
		return 3;
	});
}

void MainWindow::on_queryBtn_clicked() {
	menuBtnClicked([&] (){
			//查询当天的数据
			try {
				if (m_queryData.size() == 0) {
					queryHistoryTestParams();
					QDate today = QDate::currentDate();
					queryTestRecord(today, today);
				}
			}
			catch (const MyError& e) {
				qCritical() << e.what();
				MyMessageBox::warning(this, "数据查询失败", "关闭");
			}
			return 4;
		});
}

void MainWindow::on_aboutBtn_clicked() {
	menuBtnClicked([&]() {
		return 5;
	});
}

void MainWindow::on_startTestBtn_clicked() {
	objClicked([&] {
		//校验检测参数
		m_testData = DaoModel::TestData();
		if (checkTestParams(m_testData)) {
			//判断当前批次是否第一次检测，若是第一次检测，添加数据
			if (m_testRecord.dataList.size() == 0) {
				m_testRecord = MyModel::TestRecord(
					m_ui->mBrandComboBox->currentText().trimmed(),
					m_ui->mTesterComboBox->currentText().trimmed(),
					m_ui->mScheduleComboBox->currentText().trimmed()
				);
				//禁用输入框
				m_ui->mBrandComboBox->setEnabled(false);
				m_ui->mTesterComboBox->setEnabled(false);
				m_ui->mScheduleComboBox->setEnabled(false);
				m_ui->mTestBatchLineEdit->setEnabled(false);

				//禁止在运行期间“测量按钮被二次”点击,其他按钮也应该禁用
				m_ui->startTestBtn->setEnabled(false);//测量按钮
                m_ui->resetParamsBtn->setEnabled(false);//重置按钮
				m_ui->DrivenWheelControlBtn_2->setEnabled(false);//主轮涨紧
				m_ui->FollowedWheelControlBtn_2->setEnabled(false);//从轮涨紧
				m_ui->printTestDataBtn->setEnabled(false);//打印按钮
				m_ui->exportTestDataBtn->setEnabled(false);//导出按钮
				m_ui->deleteTestDataBtn->setEnabled(false);//删除按钮
				m_ui->clearTestDataBtn->setEnabled(false);//清空按钮
				
				try {
					m_app.saveTestRecord(m_testRecord);
				} catch (const MyError& e) {
					qCritical() << e.desc();
				}
			}                                         
			try {
				// MyLoading::startLoading();
				 //涨紧薄膜
				m_app.stretchedFilm();
				//
				//涨紧4s之后开始测试
				m_app.delay(4000, [=]() {	
				//添加检测员
				addTestParams("tester", m_testData.tester());
				//添加牌号
				addTestParams("brand", m_testData.brand());
				//添加班次
				addTestParams("schedule", m_testData.schedule());

					m_app.startTest();//开始采集        
				}, this);

				//m_app.startTest();//开始采集 采图单独用
			} catch (const MyError& e) {
				MyMessageBox::warning(this, e.desc(), "关闭");
			}
		}
	});
}

void MainWindow::on_resetParamsBtn_clicked() {
	objClicked([&] {
		//启用输入框
		m_ui->mBrandComboBox->setEnabled(true);
		m_ui->mTesterComboBox->setEnabled(true);
		m_ui->mScheduleComboBox->setEnabled(true);
		m_ui->mTestBatchLineEdit->setEnabled(true);
		//清空参数选择输入框
		m_ui->mBrandComboBox->setCurrentIndex(-1);
		m_ui->mTesterComboBox->setCurrentIndex(-1);
		m_ui->mScheduleComboBox->setCurrentIndex(-1);
		m_ui->mTestBatchLineEdit->clear();
		m_ui->mTestNumLineEdit->clear();
		m_testRecord.dataList.clear();
		// MyLoading::startLoading();
		try {
			m_app.resetPlatform();
		} catch (const MyError& e) {
			qCritical() << e.desc();
		}
		// MyLoading::stopLoading();
	});
}

void MainWindow::on_printTestDataBtn_clicked() {
	/*objClicked([&] {
		MyError error = MyError(MyErrorType::CAMERA_NOT_CONNECT);
		qDebug() << error.what();
		qDebug() << error.detail();
	});*/
	//零时测试代码
	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
	
	string pcdName = "cloud.pcd";

	if (pcl::io::loadPCDFile<pcl::PointXYZ>(pcdName, *cloud) == -1) {
		PCL_ERROR("Couldn't read file %s\n", pcdName.c_str());
		return;
	}

	// ======== 显示3D图像
	viewer->removeAllPointClouds();
	viewer->removeAllShapes();

	// 刷新渲染
	m_ui->openGLWidget->GetRenderWindow()->Render();
	viewer->setBackgroundColor(0, 0, 0);


	//设置点云颜色
	pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> fieldColor(cloud, "z");

	viewer->addPointCloud<pcl::PointXYZ>(cloud, fieldColor, "sample cloud");
	viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
	
	// 只添加一次坐标系
	static bool coordAdded = false;
	if (!coordAdded) {
		viewer->addCoordinateSystem(5.0);
		coordAdded = true;
	}
	viewer->addCoordinateSystem(5.0);
	viewer->initCameraParameters();
	viewer->resetCamera();

	// 立即渲染一次
	m_ui->openGLWidget->GetRenderWindow()->Render();

	// 仅在必要时手动刷新一次，而不是循环调用
	viewer->spinOnce(100);
}

void MainWindow::on_exportTestDataBtn_clicked() {
	objClicked([&] {
		//判断时候有数据可以导出
		if (m_testDataList.size() > 0) {
			//获取文件保存的文件夹
			QString filePath = QFileDialog::getExistingDirectory(this, QString("保存"), FileUtils::getDesktopPath());
			if (!filePath.isEmpty()) {
				//文件保存路径/项目名_检测日期_检测编号
				QString fileName=tr("%1/FOTF100_%2.xlsx").arg(filePath).arg(m_testDataList[0].createTime().toString("yyyyMMddTHHmmss"));
				try {
					ExcelUtils::saveExcel(m_testDataList, fileName);
					MyMessageBox::information(this, tr("导出完成"), tr("关闭"));
				}catch (const std::exception& e) {
					qCritical() << e.what();
					MyMessageBox::warning(this, tr("导出失败"), tr("关闭"));
				}
			}
			else {
				MyMessageBox::warning(this, tr("无可导出数据"), tr("关闭"));
				qWarning() << tr("无可导出数据");
			}
		}
	});
}

void MainWindow::on_deleteTestDataBtn_clicked() {
	objClicked([&]() {

		//检测薄膜检测数量
		int dataSize = m_testDataList.size();
		if (dataSize > 0) {
			//选中的行
			QTableWidget* mResultTable = m_ui->measureTableWidget;
			QList<QTableWidgetItem*>items = mResultTable->selectedItems();
			if (items.size() > 0 && items[0]->row() < dataSize) {
				if (MyMessageBox::warning(this, tr("是否要删除当前选中的记录，删除后无法恢复"), tr("是"), tr("否"))) {
					int index = items[0]->row();
					DaoModel::TestData& data = m_testDataList[index];
					//删除选中行
					mResultTable->removeRow(index);
					mResultTable->setRowCount(max(m_testTableMinRow, dataSize));
					try {
						m_app.deleteSqlRecord(data.id());
						m_testDataList.removeAt(index);
					}
					catch (const std::exception& e) {
						qCritical() << e.what();
					}
					//清除选择的行
					mResultTable->clearSelection();
				}
			}
		}
	});
}

void MainWindow::on_clearTestDataBtn_clicked() {
	objClicked([&]() {
		if (m_testDataList.size() > 0 && MyMessageBox::warning(this, tr("是否要删除当前检测的记录"), tr("是"), tr("否"))) {
			//删除表格中的数据
			TableUtils::restTable(m_ui->measureTableWidget, m_testTableMinRow);
			try {
				vector<qint64>dataIds;
				for (DaoModel::TestData& data : m_testDataList) {
					//删除文件
					dataIds.push_back(data.id());
				}
				m_app.deleteSqlRecords(dataIds);
				//清空缓存数据
				m_testDataList.clear();
			}
			catch (const MyError& e) {
				qCritical() << e.what();
				MyMessageBox::error(this, tr("清理失败[%1]").arg(e.what()), tr("关闭"));
			}
			catch (...) {
				qCritical() << "UNKONW ERROR";
				MyMessageBox::error(this, tr("清理失败"), tr("关闭"));
			}
		}
	});
}

void MainWindow::on_confirmMotoParamsSettingBtn_clicked() {
	objClicked([&]() {
	
		SerialPortConfig config;
		config.scannSpeed = m_ui->sScanSpeedSpinBox->value();
		config.backSpeed = m_ui->sBackSpeedSpinBox->value();
		config.eQuicken = m_ui->sEQuickenSpinBox->value();
		config.eWork = m_ui->sEWorkSpinBox->value();
		config.eAwait = m_ui->sEAwaitSpinBox->value();
		config.accelerated = m_ui->sAcceleratedSpinBox->value();
		config.retarded = m_ui->sRetardedSpinBox->value();
		config.motoMcs = m_ui->sMotoMcsSpinBox->value();
		config.serialNum = m_ui->comboBox->currentText();
		//下发参数
		// MyLoading::startLoading(); 
		try {
			m_app.update485Params(config);
			MyMessageBox::information(this, "参数下发完成", "关闭");
		} catch (const MyError& e) {
			qCritical() << e.what();
			MyMessageBox::error(this, e.desc(), "关闭");
		}
		// MyLoading::stopLoading();
	});
}

void MainWindow::on_saveMotoParamsSettingBtn_clicked() {
	objClicked([&] {
		SerialPortConfig& config = m_app.getConfig().serialPortConfig;
		config.scannSpeed = m_ui->sScanSpeedSpinBox->value();
		config.backSpeed = m_ui->sBackSpeedSpinBox->value();
		config.eQuicken = m_ui->sEQuickenSpinBox->value();
		config.eWork = m_ui->sEWorkSpinBox->value();
		config.eAwait = m_ui->sEAwaitSpinBox->value();
		config.accelerated = m_ui->sAcceleratedSpinBox->value();
		config.retarded = m_ui->sRetardedSpinBox->value();
		config.motoMcs = m_ui->sMotoMcsSpinBox->value();
		config.serialNum = m_ui->comboBox->currentText();
		if (m_ui->rotateDirComBX->currentIndex() == 0)//转动方向 第一个是正向
		{
			config.rotateDirection = 1;
		}
		else
		{
			config.rotateDirection = 0;
		}
		config.rotateCount=m_ui->rotateCountSpinBox->value();
		try {
			m_app.saveConfig();
			MyMessageBox::information(this, "保存完成", "关闭");
		} catch (const MyError& e) {
			qCritical() << e.what();
			MyMessageBox::error(this, e.desc(), "关闭");
		}
	});
}

void MainWindow::on_resetMotoParamsSettingBtn_clicked() {
	objClicked([&]() {
		resetMotoParams();
	});
}

void MainWindow::on_motoBackBtn_clicked() { 
	objClicked([&]() {
		// MyLoading::startLoading();
		//try {
		//	
		//} catch (const MyError& e) {
		//	MyMessageBox::warning(this, e.desc(), "关闭");
		//}
		// MyLoading::stopLoading();


		m_app.resetPlatform();
	});
}

void MainWindow::on_motoScannerTestBtn_clicked() {
	objClicked([&]() {
		// MyLoading::startLoading();
		//try {
		//	
		//} catch (const MyError& e) {
		//	MyMessageBox::warning(this, e.desc(), "关闭");
		//}
		//// MyLoading::stopLoading();
		m_app.movePlatformToTail();
	});
}

void MainWindow::on_stopMotoMoveBtn_clicked() { 
	objClicked([&]() {
		try {
			m_app.stopPlatformMove();
		} catch (const MyError& e) {
			MyMessageBox::warning(this, e.desc(), "关闭");
		}
	});
}

void MainWindow::on_confrimCameraSettingBtn_clicked() {
	objClicked([&]() {
		CameraConfig& config = m_app.getConfig().camera;
		config.gain = m_ui->cameraGainSpinBox->value();
		config.exposure = m_ui->cameraExposureTimeSpinBox->value();
		config.whiteBalanceRed = m_ui->cameraWBRDoubleSpinBox->value();
		config.whiteBalanceGreen = m_ui->cameraWBGDoubleSpinBox->value();
		config.whiteBalanceBlue = m_ui->cameraWBBDoubleSpinBox->value();
		config.frameWidth = m_ui->cameraFrameWidthSpinBox->value();
		config.frameHeight = m_ui->cameraFrameHeightSpinBox->value();
		config.offsetX = m_ui->cameraFrameBeginXSpinBox->value();
		config.offsetY = m_ui->cameraFrameBeginYSpinBox->value();
		config.fps = m_ui->cameraFPSSpinBox->value();
		config.frameCount = m_ui->cameraFrameCountSpinBox->value();
		try {
			m_app.setCameraParams(config);
			m_app.saveConfig();
			MyMessageBox::information(this, "保存成功", "关闭");
		} catch (const MyError& e) {
			MyMessageBox::warning(this, e.desc(), "关闭");
		}
	});
}

void MainWindow::on_resetCameraSettingBtn_clicked() {
	objClicked([&]() {
		resetCameraParams();
	});
}

void MainWindow::on_servoTestBtn_clicked()
{
	objClicked([&]() {
		//1.设置转动方向
		QString qstrRotateDirMark = QString("1");
		QString qstrRotateDir;//转动方向
		qstrRotateDir = (m_ui->rotateDirComBX->currentIndex() == 0) ? QString("1") :QString("2");
		qstrRotateDirMark.append(qstrRotateDir);
		if (qstrRotateDir == QString("1"))//正转的话，薄膜拉扯到一定力距就会停下来，如果没有薄膜就会一直转
		{
			if (m_app.servoControl(qstrRotateDirMark))
			{
				qInfo() << "转动方向设置成功";
			}
			else {

				MyMessageBox::warning(this, "伺服转动方向设置失败", "关闭");
				return;
			}
		}
		else if (qstrRotateDir == QString("2"))//反转的话，就会一直转，所以要给个停止指令
		{
			if (m_app.servoControl(qstrRotateDirMark))
			{
				qInfo() << "转动方向设置成功";
				//延迟两秒钟后再停止转动
				m_app.delay(500, [=]() {
					QString qstrStopMark = QString("1");
					QString qstrStopRotateDir;//转动方向
					qstrStopRotateDir = QString("2");
					qstrStopMark.append(qstrStopRotateDir);
					if (m_app.servoControl(qstrStopMark))
					{
						qInfo() << "停止转动成功";
					}
					else
					{
						MyMessageBox::warning(this, "停止转动失败", "关闭");
						return;
					}
				}, this);
			}
			else {

				MyMessageBox::warning(this, "伺服转动方向设置失败", "关闭");
				return;
			}
		}
		
	});
}

void MainWindow::on_stopServoRotateBtn_clicked()
{
	objClicked([&]() {
		//1.设置转动方向
		QString qstrRotateDirMark = QString("1");
		QString qstrRotateDir;//转动方向
		qstrRotateDir = QString("2");
		qstrRotateDirMark.append(qstrRotateDir);
		if (m_app.servoControl(qstrRotateDirMark))
		{
			//延迟两秒钟后再停止转动
			m_app.delay(500, [=]() {
				QString qstrStopMark = QString("1");
				QString qstrStopRotateDir;//转动方向
				qstrStopRotateDir = QString("3");
				qstrStopMark.append(qstrStopRotateDir);
				if (m_app.servoControl(qstrStopMark))
				{
                    qInfo() << "停止转动成功";
				}
				else
				{
					MyMessageBox::warning(this, "停止转动失败", "关闭");
					return;
				}
			}, this);
		}
		else {
				MyMessageBox::warning(this, "停止伺服转动方向设置失败", "关闭");
				return;
		}
	});
}

void MainWindow::on_DrivenWheelControlBtn_2_clicked()
{
	QString labText= m_ui->DrivenWheelControlBtn_2->text();
	if (labText == QString("主轮涨紧")) {
		QString activeControl = QString("2");
		if (m_app.activeWheelControl(activeControl)) {
			m_ui->DrivenWheelControlBtn_2->setText("主轮松弛");
		}
	}
	else if (labText == QString("主轮松弛")) {
		QString activeControl = QString("1");
		if (m_app.activeWheelControl(activeControl)) {
			m_ui->DrivenWheelControlBtn_2->setText("主轮涨紧");
		}
	}
}

void MainWindow::on_FollowedWheelControlBtn_2_clicked()
{
	QString labText = m_ui->FollowedWheelControlBtn_2->text();
	if (labText == QString("从轮涨紧")) {
		QString follwedControl = QString("2");
		if (m_app.passiveWheelControl(follwedControl)) {
			m_ui->FollowedWheelControlBtn_2->setText("从轮松弛");
		}
	}
	else if (labText == QString("从轮松弛")) {
		QString follwedControl = QString("1");
		if (m_app.passiveWheelControl(follwedControl)) {
			m_ui->FollowedWheelControlBtn_2->setText("从轮涨紧");
		}
	}
}

void MainWindow::on_qConfirmBtn_clicked()
{
	//输入检测日期
	QDate beginDate=m_ui->qBeginDateEdit->date();
	QDate endDate=m_ui->qEndDateEdit->date();
	if (endDate < beginDate) {
        MyMessageBox::warning(this, tr("结束日期不能小于开始日期"), "关闭");
		return;
	}
	try {
		//查询结果
		QComboBox* qTesterComboBox = m_ui->qTesterComboBox;
		QComboBox* qScheduleComboBox = m_ui->qScheduleComboBox;
		queryTestRecord(beginDate, endDate, qTesterComboBox->currentText(), qScheduleComboBox->currentText());
		
	}
	catch(const MyError& e) {
		qCritical() << e.what();
	}
	catch (const std::exception& e) {

	}

}

void MainWindow::on_qResetBtn_clicked()
{
	//重置日期
	QDate today = QDate::currentDate();
	m_ui->qBeginDateEdit->setDate(today);
	m_ui->qEndDateEdit->setDate(today);
	//重置检测员、牌号，班次信息
	m_ui->qTesterComboBox->setCurrentIndex(-1);
	m_ui->qScheduleComboBox->setCurrentIndex(-1);

	//清空所有表格的选中行
	m_ui->qResultTable->clearSelection();
	m_ui->qResultTable_2->clearSelection();
}

void MainWindow::on_qExportBtn_clicked()
{
	objClicked([&]() {
	
		//获取选中行
		qDebug() << "Selection Mode:" << m_ui->qResultTable->selectionMode();
		qDebug() << "Selection Behavior:" << m_ui->qResultTable->selectionBehavior();
		if (m_ui->qResultTable->currentRow() == -1) {
			qDebug() << "没有选中行";
		}
		else {
			qDebug() << "选中行" << m_ui->qResultTable->currentRow();
		}

		QList<QTableWidgetItem*>items = m_ui->qResultTable->selectedItems();//选中行所有项内容
		qDebug() <<"items.size()="<< items.size();
		if (items.size() > 0) {
			//获取行号
			int row = items[0]->row();
			//判断表格当前选择的行是否有数据
			if (m_queryData.size() > 0) {
				//获取文件保存的路径
				QString filePath = QFileDialog::getExistingDirectory(this, QString("保存"), FileUtils::getDesktopPath());
				if (!filePath.isEmpty()) {
					//文件保存路径/项目名_检测日期_检测编号
					QString fileName = tr("%1/FOTF100_%2.xlsx").arg(filePath).arg(m_queryData[0].createTime().toString("yyyyMMddHHmmsss"));
					try {
						ExcelUtils::saveExcel(m_queryData, fileName);
						MyMessageBox::information(this, tr("导出完成"), tr("关闭"));
					}
					catch (const std::exception& e) {
						qCritical() << e.what();
						MyMessageBox::warning(this, tr("导出失败"), tr("关闭"));
					}
				}
			}
			else {
				MyMessageBox::warning(this, tr("无可导出数据"), tr("关闭"));
				qWarning() << tr("无可导出数据");
			}

		}
		else {
			MyMessageBox::information(this, "请先选择要导出的数据", "关闭");
		}
	});
}

void MainWindow::on_qPrintBtn_clicked()
{
	objClicked([&]() {
		QList<QTableWidgetItem*> items = m_ui->qResultTable->selectedItems();
		if (items.size() > 0) {
			//获取行编号
			int row = items[0]->row();
			//判断表格当前选择的行是否有数据
			if (m_queryData.size() > 0) {
				PrinterManager::printDirect(m_queryData);
			}
			else {
				MyMessageBox::warning(this, tr("没有可打印的数据"), tr("关闭"));
				qWarning() << tr("没有数据可打印");
			}
		}
		else {
			MyMessageBox::information(this, "请先选择要打印的数据", "关闭");
		}
    });
}

void MainWindow::on_qDeleteBtn_clicked()
{
	objClicked([&]() {
		QTableWidget* table = m_ui->qResultTable_2;
		QList<QTableWidgetItem*>& items = table->selectedItems();
		//判断当前选中的行是是否在数据范围内
		if (items.size() > 0 && items[0]->row() < m_queryData.size()) {
			int row = items[0]->row();
			if (MyMessageBox::warning(this, tr("是否要删除当前选择的记录"), tr("是"), tr("否"))) {
				try {
					//删除表格中的数据
					table->removeRow(row);
					table-> setRowCount(max(m_historyDataTableMinRow, m_queryData.size()));
					table->clearSelection();
					DaoModel::TestData& data = m_queryData[row];
					//删除数据库中的数据
					m_app.deleteSqlRecord(data.id());
					//删除缓存
					m_queryData.removeAt(row);
					//判断表格中的数据是否全部被删除玩了
					if (m_queryData.empty()) {
						//重新查询检测记录
						queryTestRecord(
							m_ui->qBeginDateEdit->date(),
							m_ui->qEndDateEdit->date(),
							m_ui->qTesterComboBox->currentText(),
							m_ui->qScheduleComboBox->currentText());
						m_ui->qResultTable->clearSelection();
					}

				}catch (const MyError& e) {
					qCritical() << e.what();
					MyMessageBox::error(this, tr("删除失败[%1]").arg(e.what()), "关闭");
				}catch (...) {
					qCritical() << "UNKNOW ERROR";
					MyMessageBox::error(this, tr("删除失败"), "关闭");
				}
			}
		}
		else {
			MyMessageBox::warning(this,"未发现检测记录","关闭");
		}
	});
}

void MainWindow::on_qResultTable_cellClicked(int row, int column)
{
	qInfo() << QString("on_qResultTable_cellClicked:[row:%1,column:%2]").arg(row).arg(column);
	/*objClicked([&]() {
		
	});*/
	try {
		qDebug() << "search begin";
		//清空结果表格
		QTableWidget* dataTable = m_ui->qResultTable_2;
		TableUtils::restTable(dataTable, m_historyDataTableMinRow);
		//清空查询数据缓存
		m_queryData.clear();
		//获取发送事件的表格
		QTableWidget* table = qobject_cast<QTableWidget*>(sender());
		//获取当前选中的行是否有数据
		QTableWidgetItem* item = table->item(row, 0);
		if (item != nullptr && !item->text().isEmpty()) {
			//查询检测记录
			m_app.querySqlTestData(m_queryData, table->item(row, 0)->text());
			if (m_queryData.size() > 0) {
				qDebug() << "is here ";
				m_app.showTestData(dataTable, m_queryData, m_historyDataTableMinRow);
			}
		}
	}
	catch (const MyError& e) {

		qCritical() << e.what();
		MyMessageBox::error(this, tr("查询失败[%1]").arg(e.what()), "关闭");
	}
	catch (...) {
		qCritical() << "UNKNOW ERROR";
		MyMessageBox::error(this, tr("查询失败"), "关闭");
	}
}


